package controller

import (
	"danmu/common"
	"danmu/dto"
	"danmu/model"
	"danmu/response"
	"github.com/gin-gonic/gin"
)

func GetAnnounce(ctx *gin.Context) {
	DB := common.GetDB()
	var oldTime model.AnnounceUser
	var newAnnounce []model.Announce
	//从上下文中获取用户id
	id, _ := ctx.Get("id")
	//最后一次获取的时间
	DB.Where("uid = ? ", id.(uint)).Last(&oldTime)
	//查询最后一次获取后的公告
	DB.Where("updated_at > ? ", oldTime.CreatedAt).Find(&newAnnounce)
	if newAnnounce != nil{
		for i := 0; i < len(newAnnounce); i++ {
			var newUserAnn = model.AnnounceUser{
				Aid: newAnnounce[i].ID,
				Uid: id.(uint),
			}
			DB.Create(&newUserAnn)
		}
	}
	//拉取用户公告
	var announceList []model.AnnounceUser
	DB.Where("uid = ? ", id.(uint)).Find(&announceList)
	response.Success(ctx, gin.H{"data": dto.ToAnnounceDto(announceList)}, "获取成功")
}

